package org.zhangkun.jmsg.ui.swing;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

import org.zhangkun.jmsg.core.network.filetransport.FileTransport;
import org.zhangkun.jmsg.core.network.filetransport.ReceiveFiles;
import org.zhangkun.jmsg.util.FileUtil;

public class FileTransportViewDialog extends JFrame implements Runnable {
	public class thisItemRenderer extends DefaultTableCellRenderer {
		/**
		 * 
		 */
		private static final long serialVersionUID = -5464736717870355405L;
		private long allDownSpeed;
		private long allUpSpeed;

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			// TODO Auto-generated method stub
			// Color color;
			// if (row % 2 == 0)
			// color = new Color(206, 231, 255);
			// else
			// color = new Color(255, 255, 255);
			// if (isSelected)
			// color = new Color(184, 207, 229);
			// setBackground(color);
			//
			if (isSelected) {
				setBackground(table.getSelectionBackground());
				setForeground(table.getSelectionForeground());
			} else {
				setBackground(table.getBackground());
				setForeground(table.getForeground());
			}

			FileTransport ft = allTransport.get(row);

			// if (column == 0) {
			// System.out.println("0");
			// JLabel img = new JLabel();
			// if (ft instanceof SendFiles) {
			// img.setIcon(new ImageIcon(Res.UP_IMG));
			// return img;
			// } else {
			// img.setIcon(new ImageIcon(Res.DOWN_IMG));
			// return img;
			// }
			// } else {
			// column--;
			// }

			if (row == 0 && column == 5) {
				allDownSpeed = 0;
				allUpSpeed = 0;
			}

			if (isSelected) {
				if (ft.getStatus() == FileTransport.STATUS_RUNNING) {
					long fl = ft.getCurrentFileLength();
					fl = fl == 0 ? 1 : fl;
					long frl = ft.getCurrentFileReadLength();
					currentFileInfo.setText("当前文件：" + ft.getCurrentFileName()
							+ " (" + FileUtil.getSizeStr(frl) + "/"
							+ FileUtil.getSizeStr(fl) + " " + (frl * 100) / fl
							+ "%)");
				} else {
					currentFileInfo.setText("");
				}
			}

			if (column == 1) {
				value = (getStatus(ft.getStatus()));
			} else {
				if (ft.getStatus() == FileTransport.STATUS_RUNNING) {
					switch (column) {
					case 3:
						value = ft.getFileName();
						if (value == null)
							value = "";
						break;
					case 4:
						long cfl = ft.getCurrentTransportSize();
						long crl = (ft.getCurrentTransportReadSize());
						if (cfl != 0)
							value = ("" + ((crl * 100) / cfl) + "% "
									+ FileUtil.getSizeStr(crl) + "/" + FileUtil
									.getSizeStr(cfl));
						else
							value = (FileUtil.getSizeStr(crl) + "/-");
						break;
					case 5:
						long spd = ft.getSpeed();
						if (ft instanceof ReceiveFiles)
							allDownSpeed += spd;
						else
							allUpSpeed += spd;
						value = (FileUtil.getSizeStr(spd) + "/s");
						break;
					case 6:

						long cfl1 = ft.getAllSize();
						long crl1 = (ft.getAllReadSize());
						if (cfl1 != 0)
							value = (ft.getIndex() + 1) + "/" + ft.getFmpSize()
									+ " " + ((crl1 * 100) / cfl1) + "% "
									+ FileUtil.getSizeStr(crl1) + "/"
									+ FileUtil.getSizeStr(cfl1);
						else
							value = (ft.getIndex() + 1) + "/" + ft.getFmpSize()
									+ " " + FileUtil.getSizeStr(crl1) + "/-";
						break;
					}

				} else if (column == 3 || column == 4 || column == 5
						|| column == 6) {
					value = "-";
				}
			}
			if (row == dtm.getRowCount() - 1) {
				FileTransportViewDialog.this.allDownSpeed.setText("下载:"
						+ FileUtil.getSizeStr(allDownSpeed) + "/s");
				FileTransportViewDialog.this.allUpSpeed.setText("上传:"
						+ FileUtil.getSizeStr(allUpSpeed) + "/s");
			}
			setHorizontalAlignment(CENTER);
			return super.getTableCellRendererComponent(table, value,
					isSelected, hasFocus, row, column);
		}
	}

	private static final ArrayList<FileTransport> allTransport = new ArrayList<FileTransport>();
	public static FileTransportViewDialog instance;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1936352830252758964L;

	public synchronized static void addFileTransport(FileTransport ft) {
		create();
		instance.addTransport(ft);
	}

	public synchronized static FileTransportViewDialog create() {
		if (instance == null) {
			instance = new FileTransportViewDialog();
		}
		return instance;
	}

	private JLabel allDownSpeed;

	private JLabel allUpSpeed;

	private final JPanel contentPanel = new JPanel();
	private JLabel currentFileInfo;

	private DefaultTableModel dtm = new DefaultTableModel() {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1467430230543231722L;

		@Override
		public boolean isCellEditable(int row, int column) {
			// TODO Auto-generated method stub
			return false;
		}

	};

	private JButton fileBtn;

	private boolean isShow = true;

	private JPanel panel_1;

	private JButton retryBtn;

	private JButton stopBtn;

	private JTable table;

	/**
	 * Create the dialog.
	 */
	public FileTransportViewDialog() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(
				FileTransportViewDialog.class
						.getResource("/res/system-file-manager.png")));
		setBounds(100, 100, 731, 476);
		setTitle("文件传输管理器");
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new BorderLayout(0, 0));
		{
			JScrollPane scrollPane = new JScrollPane();
			contentPanel.add(scrollPane, BorderLayout.CENTER);
			{
				table = new JTable();
				table.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent e) {
						updateCmd();
					}
				});
				initTable();
				scrollPane.setViewportView(table);
			}
		}
		{
			JPanel panel = new JPanel();
			panel.setBorder(new TitledBorder("信息："));
			contentPanel.add(panel, BorderLayout.SOUTH);
			panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
			{
				currentFileInfo = new JLabel();
				currentFileInfo.setHorizontalAlignment(SwingConstants.LEFT);
				panel.add(currentFileInfo);
			}
			{
				panel_1 = new JPanel();
				panel.add(panel_1);
				panel_1.setLayout(new GridLayout(0, 2, 0, 0));
				{
					allUpSpeed = new JLabel();
					panel_1.add(allUpSpeed);
				}
				{
					allDownSpeed = new JLabel();
					panel_1.add(allDownSpeed);
				}
			}
		}
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setBorder(new EmptyBorder(0, 10, 10, 10));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton closeBtn = new JButton("关闭");
				closeBtn.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						FileTransportViewDialog.this.dispose();
					}
				});
				BorderLayout bl = new BorderLayout(0, 0);
				// bl.setHgap(10);
				// bl.setVgap(10);
				buttonPane.setLayout(bl);
				closeBtn.setActionCommand("OK");
				buttonPane.add(closeBtn, BorderLayout.EAST);
				getRootPane().setDefaultButton(closeBtn);
			}
			{
				JPanel panel = new JPanel();
				buttonPane.add(panel, BorderLayout.CENTER);
				panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
				{
					stopBtn = new JButton("终止");
					panel.add(stopBtn);
				}
				{
					fileBtn = new JButton("文件");
					panel.add(fileBtn);
				}
				{
					retryBtn = new JButton("重试");
					panel.add(retryBtn);
				}
			}
		}
		updateCmd();
		new Thread(this, "FileTransportView Thread").start();
	}

	public void addTransport(FileTransport ft) {
		Vector<String> row = new Vector<String>();
		row.add(ft.getWorkName());
		row.add(getStatus(ft.getStatus()));
		row.add(ft.getUser().getName());
		row.add(ft.getCurrentFileName());
		long cfl = ft.getCurrentFileLength();
		long crl = (ft.getCurrentReadLength());
		if (cfl != 0)
			row.add((crl * 100) / cfl + "%");
		else
			row.add("");
		row.add(FileUtil.getSizeStr(ft.getSpeed()));
		row.add((ft.getIndex() + 1) + "/" + ft.getFmpSize());
		allTransport.add(ft);
		dtm.addRow(row);
	}

	public JLabel getCurrentFileInfo() {
		return currentFileInfo;
	}

	public JButton getFileBtn() {
		return fileBtn;
	}

	public JButton getRetryBtn() {
		return retryBtn;
	}

	private String getStatus(int status) {
		switch (status) {
		case FileTransport.STATUS_ERROR:
			return "传送失败";
		case FileTransport.STATUS_FINISH:
			return "完成";
		case FileTransport.STATUS_RUNNING:
			return "传送中";
		case FileTransport.STATUS_WAITFORSTART:
			return "等待开始";
		case FileTransport.STATUS_USER_CANCEL:
			return "用户取消";
		case FileTransport.STATUS_BY_STOP:
			return "对方取消";
		}
		return "";
	}

	public JButton getStopBtn() {
		return stopBtn;
	}

	private void initTable() {
		// TODO Auto-generated method stub
		table.setDefaultRenderer(Object.class, new thisItemRenderer());
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		// dtm.addColumn("");
		dtm.addColumn("操作");
		dtm.addColumn("状态");
		dtm.addColumn("用户");
		dtm.addColumn("当前传送");
		dtm.addColumn("当前");
		dtm.addColumn("速度");
		dtm.addColumn("全部");
		for (int i = 0; i < allTransport.size(); i++)
			addTransport(allTransport.get(i));
		table.setModel(dtm);
		table.getColumn("操作").setPreferredWidth(30);
		table.getColumn("状态").setPreferredWidth(50);
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (isShow) {
			this.repaint();
			try {
				Thread.sleep(1010);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void updateCmd() {
		updateCmd(false);
		int selIndex = table.getSelectedRow();
		if (selIndex < 0 || selIndex > allTransport.size() - 1) {
			return;
		}
		FileTransport ft = allTransport.get(selIndex);
		if (ft.getStatus() == FileTransport.STATUS_ERROR) {
			retryBtn.setEnabled(true);
		}
		if (ft.getStatus() == FileTransport.STATUS_FINISH) {
			fileBtn.setEnabled(true);
		}

		if (ft.getStatus() == FileTransport.STATUS_RUNNING) {
			stopBtn.setEnabled(true);
		}

	}

	private void updateCmd(boolean flag) {
		stopBtn.setEnabled(flag);
		fileBtn.setEnabled(flag);
		retryBtn.setEnabled(flag);
	}
}
